<template>
  <view class="map-container">
    <map id="myMap" ref="mapRef" :longitude="longitude" :latitude="latitude" :scale="scale" show-location @markertap="markerTap" style="height: 100%; width: 100%" />
  </view>
</template>

<script>
import mapMarkIcon from '@/static/images/map/normal-marker-icon.png'
export default {
  name: 'Map',
  data() {
    return {
      mapMarkIcon,
      mapContent: null,
      scale: 12
    }
  },
  props: {
    markLongLatList: {
      type: Array,
      default: () => {}
    },
    longitude: {
      type: Number,
      default: 120.13282288525389
    },
    latitude: {
      type: Number,
      default: 30.25900420950505
    }
  },

  watch: {
    markLongLatList: {
      deep: true,
      handler(newVal) {
        this.createMarkerCluster()
      }
    }
  },
  created() {
    this.mapContent = uni.createMapContext('myMap', this)
    uni.getLocation({
      success: res => {},
      fail: err => {}
    })
  },
  methods: {
    createMarkerCluster() {
      const that = this
      that.mapContent.initMarkerCluster({
        enableDefaultStyle: true,
        zoomOnClick: false,
        gridSize: 40,
        complete(res) {
          const marker = {
            width: 15,
            height: 15,
            joinCluster: true
          }
          let newMarkers = []
          that.markLongLatList.forEach((item, index) => {
            newMarkers.push({ id: index + 1, ...marker, ...item })
          })
          that.mapContent.addMarkers({
            markers: newMarkers,
            clear: true,
            complete(markersInfo) {
              console.log(markersInfo)
            }
          })
        }
      })
      that.mapContent.on('markerClusterCreate', clusterInfo => {
        console.log('markerClusterCreate')
      })
      that.mapContent.on('markerClusterClick', clusterInfo => {
        uni.$emit('getClusterInfo', clusterInfo.cluster)
      })
    },
    async moveToLocaltion(latitude, longitude) {
      this.mapContent.moveToLocation({ latitude, longitude })
      this.mapContent
        .getScale()
        .then(res => {
          this.scale = res.scale
        })
        .finally(() => {
          this.scale = 17
        })
    },
    markerTap(info) {
      const obj = this.markLongLatList.find(item => item.id === info.markerId)
      uni.navigateTo({ url: `/subPackages/assets-manage/detail/index?id=${obj.id}` })
    }
  }
}
</script>

<style lang="scss">
.map-container {
  width: 100%;
  height: 100%;
}
</style>
